from uuid import uuid4

from fastapi import FastAPI
from fastapi.requests import Request

from utils.helper import load_yaml
from utils.logger import thread_logger
from utils.paths import SYSTEM_CONFIG_PATH


def emit_global_variable(app: FastAPI):
    """
    注入全局变量
    """
    @app.middleware("http")
    async def add_custom_variable_to_request(request: Request, call_next):
        request_id = uuid4().hex
        system_config = load_yaml(SYSTEM_CONFIG_PATH)

        # 注入全局变量
        request.state.debug = system_config.get('DEBUG', False)
        request.state.request_id = request_id
        request.state.logger = thread_logger(request_id)

        response = await call_next(request)
        return response